<template>
  <div id="addStaff">
    <el-form ref="form" :model="form" status-icon :rules="rules" label-width="80px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="身份证号" prop="card">
        <el-input v-model="form.card" />
      </el-form-item>
      <el-form-item label="所属部门" prop="role">
        <el-select v-model="form.role" placeholder="请选择活动区域">
          <el-option label="维修部" value="维修部" />
          <el-option label="业务部" value="业务部" />
          <el-option label="行政部" value="行政部" />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio label="男" />
          <el-radio label="女" />
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">确定</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import staffApi from '../../api/staff.js'

export default {
  data() {
    // 验证电话号码
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('联系电话不能为空'))
      }
      setTimeout(async() => {
        const data = await staffApi.checkPhone({ phone: value })
        if (data) {
          callback(new Error('电话号码已存在'))
        } else {
          callback()
        }
      }, 1000)
    }
    // 验证身份证
    var validateCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('身份证不能为空'))
      }
      setTimeout(async() => {
        const data = await staffApi.checkCard({ card: value })
        if (data) {
          callback(new Error('身份证号已存在'))
        } else {
          callback()
        }
      }, 1000)
    }
    return {
      form: {
        name: '',
        phone: '',
        role: '',
        card: '',
        gender: '',
        pwd: '111111'
      },
      rules: {
        phone: [{ validator: validatePhone, trigger: 'blur' }],
        card: [{ validator: validateCard, trigger: 'blur' }]
      }
    }
  },
  methods: {
    async onSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          await staffApi.addOne(this.form)
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.form = {
            name: '',
            phone: '',
            role: '',
            card: '',
            gender: '',
            pwd: ''
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
#addStaff {
  width: 90%;
  margin: auto;
  margin-top: 30px;
}
</style>
